import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
import uuid
import os
import io
import datetime
from PIL import Image
import urllib.request
import requests

os.environ['OSS_ACCESS_KEY_ID'] = 'LTAI5tM8qSXhHc2eVF11m67y'
os.environ['OSS_ACCESS_KEY_SECRET'] = '6XtBvI5w2LU4OJA4dpNprVZuZoy4d0'

aliyun_prefix = 'http://msjava.oss-cn-qingdao.aliyuncs.com'


def download_file_to_temp_folder(file_path, temp_folder):
    """
    会对文件重新命名
    :param file_path:  文件链接最后面必须有对应的文件类型  .jpg  .txt等等
    :param temp_folder:
    :return:
    """
    file_type = file_path.split('.')[-1]
    if not os.path.exists(temp_folder):
        os.makedirs(temp_folder)

    temp_name = os.path.join(temp_folder, f'{uuid.uuid4()}.{file_type}')
    urllib.request.urlretrieve(file_path, temp_name)
    return temp_name


def upload_image(img):
    """

    :param img: h,w,c  0-255
    :return:
    """
    pass
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    endpoint = "https://oss-cn-qingdao.aliyuncs.com"
    region = "cn-qingdao"
    bucket = oss2.Bucket(auth, endpoint, "msjava", region=region)
    img = Image.fromarray(img)
    byte_stream = io.BytesIO()
    img.save(byte_stream, 'PNG')
    byte_stream.seek(0)

    upload_path = f'inference/segment/{datetime.datetime.now().strftime("%Y/%m/%d")}/{uuid.uuid4()}.png'
    bucket.put_object(upload_path, byte_stream)
    return aliyun_prefix + '/' + upload_path


def upload_context2file(content, path):
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    endpoint = "https://oss-cn-qingdao.aliyuncs.com"
    region = "cn-qingdao"
    bucket = oss2.Bucket(auth, endpoint, "msjava", region=region)

    bucket.put_object(path, content)


def upload_local_file(file_path):
    """
    上传本地文件至oss
    :param file_path: 本地文件路径
    :return: oss链接
    """
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    endpoint = "https://oss-cn-qingdao.aliyuncs.com"
    region = "cn-qingdao"
    bucket = oss2.Bucket(auth, endpoint, "msjava", region=region)

    type = file_path.split('.')[-1]
    upload_path = f'{datetime.datetime.now().strftime("%Y/%m/%d")}/{uuid.uuid4()}.{type}'

    bucket.put_object_from_file(upload_path, file_path)

    return aliyun_prefix + '/' + upload_path


def download_file(url, local_filename):
    """
    针对权重下载解决方案
    :param url:
    :param local_filename:
    :return:
    """
    # 发送 GET 请求
    response = requests.get(url, stream=True)

    # 检查请求是否成功
    if response.status_code == 200:
        # 以二进制模式写入文件
        with open(local_filename, 'wb') as file:
            for chunk in response.iter_content(chunk_size=8192):  # 分块写入
                file.write(chunk)
        print(f"文件已保存至: {local_filename}")
    else:
        print(f"下载失败，状态码: {response.status_code}")


class Logger:
    def __init__(self):
        auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
        endpoint = "https://oss-cn-qingdao.aliyuncs.com"
        region = "cn-qingdao"
        self.bucket = oss2.Bucket(auth, endpoint, "msjava", region=region)
        self.upload_path = f'train/log/{datetime.datetime.now().strftime("%Y/%m/%d")}/{uuid.uuid4()}.txt'
        self.next_position = 0
        self.link = aliyun_prefix + '/' + self.upload_path

    def log(self, msg):
        print(msg)
        result = self.bucket.append_object(self.upload_path, self.next_position, msg + '\n')
        self.next_position = result.next_position


if __name__ == '__main__':
    download_file(
        'http://msjava.oss-cn-qingdao.aliyuncs.com/train/log/2024/12/27/33582b55-92b1-4809-a3a5-06bd3d465ed6.txt',
        'a.txt')
